package com.situ.company.web220111.employee.servlet;

import com.situ.company.web220111.employee.model.EmployeeModel;
import com.situ.company.web220111.employee.service.IEmployeeService;
import com.situ.company.web220111.employee.service.Impl.EmployeeServiceImpl;
import com.situ.company.web220111.util.FmtEmpty;
import com.situ.company.web220111.util.FmtRequest;
import com.situ.company.web220111.util.FmtUpload;
import org.apache.commons.fileupload.FileUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/EmployeeUploadServlet")
public class EmployeeUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private IEmployeeService service = new EmployeeServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, Object> map = null;
        try {
            map = FmtUpload.upload(request);
        } catch (FileUploadException | IOException e) {
            e.printStackTrace();
        }
        String code = map.get("code").toString();
        List<String> filenames = (List<String>) map.get(FmtUpload.FILE_NAMES);
        String image = filenames.get(0);

        EmployeeModel model = new EmployeeModel(code);

        // 实现修改/覆盖功能
        EmployeeModel mdb = service.selectModel(model);
        if (!FmtEmpty.isEmpty(mdb.getImage())) {
            FmtUpload.delFile(mdb.getImage());
        }

        model.setImage(image);
        String res = service.update(model);

        Map<String, String> result = new HashMap<String, String>();
        result.put("code", res);
        result.put("image", image);
        FmtRequest.write(response.getWriter(), result);
    }
}

